
package com.ly.credit.service;


import com.google.gson.Gson;
import com.ly.credit.dao.ApiDao;
import com.ly.credit.entity.Api;
import com.ly.credit.entity.User;
import com.ly.credit.entity.UserApi;
import com.ly.credit.util.AdResult;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("apiService")
@Transactional
public class ApiServiceImpl implements ApiService {
	@Resource
	private ApiDao apiDao;
	@Resource
	private UserApiService userApiService;
	@Resource
	private UserService userService;
	@Resource
	private HttpServletRequest request;
	public static final String ACCOUNT = "15862825196";
	public static final String PASSWORD = "wxx931029";
	public static final String REQUEST_TYPE_SECRET = "1";
	public static final String REQUEST_TYPE_VERIFY = "2";
	public static final int JIEDAIBAO = 1;
	public static final int YOUPINGZHENG = 2;
	public static final int NIFANG = 3;
	public static final int PINGZHENGYUN = 4;
	public static final int MICANG = 5;
	public static final int JINJIEDAO = 6;
	public static final int WUYOUJIETIAO = 7;
	public static final String GETCODE_API_URL = "http://47.97.207.166/verifycode";
	public static final String GET_DATA_API_URL = "http://47.97.207.166/login";
	@Transactional
	public AdResult getAll() {
		AdResult result = new AdResult();
		List<Api> apiList = apiDao.getAll();
		HttpSession session = request.getSession();
		User user =(User) session.getAttribute("user");
		if(user==null){
			result.setStatus(2);
			result.setMsg("未登录!");
			return result;
		}else{
			AdResult userApi = userApiService.getUserApi(user.getId().toString());
			List<UserApi> userApiList =(List<UserApi>) userApi.getData();
			for (Api api :apiList){
				for (UserApi userapi:userApiList){
					if(userapi.getApiId().equals(api.getId().toString())){
						api.setStatus(1);
					}
				}
			}
			result.setStatus(1);
			result.setData(apiList);
			result.setMsg("获取成功!");
			return result;
		}

	}
	public AdResult getByApiId(Integer apiId){
		AdResult result = new AdResult();
		Api api = apiDao.getByApiId(apiId);

		result.setStatus(1);
		result.setData(api);
		result.setMsg("获取成功!");
		return result;
	}
	public Api getByApiValue(Integer apiValue){
		AdResult result = new AdResult();
		Api api = apiDao.getByApiValue(apiValue);
		return api;
	}
	@Transactional
	public JSONObject getApiData(String phone, String appkey, String account, Integer apiValue, String password){
		JSONObject json = new JSONObject();
		//业务层
		User user = new User();
		user.setAppkey(appkey);
		user.setPhone(phone);
		AdResult result = userService.getUserByPhoneAppkey(user);
		if(result.getStatus()==0){
			json.put("error",10001);
			return json;
		}

		Map<String, String> urlmap = new HashMap<String, String>();
		urlmap.put("account", account);
		urlmap.put("method", REQUEST_TYPE_SECRET);
		urlmap.put("password", password);
		String apiValues="2,4,7";
		if(apiValues.contains(apiValue.toString())){
			urlmap.put("class", apiValue.toString());
		}else{
			json.put("error","10002");
			return json;
		}

		String data = this.sendGet(GET_DATA_API_URL, urlmap,request);
		json = JSONObject.fromObject(data.replaceAll("null", ""));
		String error = (String)json.get("error");
		if("ok".equals(error)){
			//扣费逻辑
			User findUser = (User)result.getData();
			Api api = this.getByApiValue(apiValue);
			if(findUser.getBalance().compareTo(api.getPrice())<0){
				json.put("error","10005");
				return json;
			}
			findUser.setBalance(findUser.getBalance().subtract(api.getPrice()));

			try {
				userService.updateUser(findUser);
			}catch (Exception e){
				e.printStackTrace();
				json.put("error","10004");
				return json;
			}

		}else{
			json.put("error","10003");
		}
		return json;
	}
	@Transactional
	public JSONObject getApiDataVerify(String phone,String appkey,String account, Integer apiValue,String verifycode){
		JSONObject json = new JSONObject();
		//业务层
		User user = new User();
		user.setAppkey(appkey);
		user.setPhone(phone);
		AdResult result = userService.getUserByPhoneAppkey(user);
		if(result.getStatus()==0){
			json.put("error",10001);
			return json;
		}

		Map<String, String> urlmap = new HashMap<String, String>();
		urlmap.put("phone", account);
		urlmap.put("method", REQUEST_TYPE_VERIFY);
		urlmap.put("verifycode", verifycode);
		urlmap.put("class", "1");
		String apiValues="1,3,5,6";
		if(apiValues.contains(apiValue.toString())){
			urlmap.put("class", apiValue.toString());
		}else{
			json.put("error","10002");
			return json;
		}

		String data = this.sendGet(GET_DATA_API_URL, urlmap,request);
		json = JSONObject.fromObject(data.replaceAll("null", ""));
		String error = (String)json.get("error");
		if("ok".equals(error)){
			//扣费逻辑
		}else{
			json.put("error","10003");
		}
		return json;
	}
	public JSONObject getVerify(String phone){
		JSONObject json = new JSONObject();
		Map<String, String> urlmap = new HashMap<String, String>();
		urlmap.put("class", "1");
		urlmap.put("phone", phone);

		String data = this.sendGet(GETCODE_API_URL, urlmap,request);
		json = JSONObject.fromObject(data);
		String error = (String)json.get("error");
		if("ok".equals(error)){
		}else{
			json.put("error","网络错误，请稍后再试！");
		}
		return json;
	}

	public static String sendPost(String url, Map<String, String> urlParameters, Map<String, String> requestParameters) {
		String result = "";// 返回的结果
		BufferedReader in = null;// 读取响应输入流
		PrintWriter out = null;
		StringBuffer sb = new StringBuffer();// 处理请求参数
		String params = "";// 编码之后的参数
		try {
			// 编码请求参数
			if (urlParameters.size() == 1) {
				for (String name : urlParameters.keySet()) {
					sb.append(name).append("=").append(
							java.net.URLEncoder.encode(urlParameters.get(name),
									"UTF-8"));
				}
				params = sb.toString();
			} else {
				for (String name : urlParameters.keySet()) {
					sb.append(name).append("=").append(
							java.net.URLEncoder.encode(urlParameters.get(name),
									"UTF-8")).append("&");
				}
				String temp_params = sb.toString();
				if (temp_params.length() > 1) {
					params = temp_params.substring(0, temp_params.length() - 1);
				} else {

				}

			}
			// 创建URL对象
			url+=params;
			java.net.URL connURL = new java.net.URL(url);
			// 打开URL连接
			java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL
					.openConnection();
			// 设置通用属性

			httpConn.setRequestProperty("Content-type", "application/json;charset=utf-8");

			// 设置POST方式
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			// 获取HttpURLConnection对象对应的输出流
			out = new PrintWriter(httpConn.getOutputStream());
			Gson gson = new Gson();
			// 发送请求参数
			String s = gson.toJson(requestParameters);
			out.write(s);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应，设置编码方式
			in = new BufferedReader(new InputStreamReader(httpConn
					.getInputStream(), "UTF-8"));
			String line;
			// 读取返回的内容
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	public static String sendGet(String url, Map<String, String> parameters,HttpServletRequest request) {
		String result = "";// 返回的结果
		BufferedReader in = null;// 读取响应输入流
		StringBuffer sb = new StringBuffer();// 存储参数
		String params = "";// 编码之后的参数
		try {
			// 编码请求参数
			if (parameters.size() == 1) {
				for (String name : parameters.keySet()) {
					sb.append(name).append("=").append(
							java.net.URLEncoder.encode(parameters.get(name),
									"utf-8"));
				}
				params = sb.toString();
			} else {
				for (String name : parameters.keySet()) {
					sb.append(name).append("=").append(
							java.net.URLEncoder.encode(parameters.get(name),
									"utf-8")).append("&");
				}
				String temp_params = sb.toString();
				params = temp_params.substring(0, temp_params.length() - 1);
			}
			String full_url = url + "?" + params;
			System.out.println(full_url);
			// 创建URL对象
			java.net.URL connURL = new java.net.URL(full_url);
			// 打开URL连接
			java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL
					.openConnection();
			// 设置通用属性
			httpConn.setRequestProperty("Content-type", "application/json;charset=utf-8");
			HttpSession session1 = request.getSession();
			if(session1.getAttribute("Cookie")!=null){
				Object cookie = session1.getAttribute("Cookie");
				String cookies=(String)cookie;
				httpConn.addRequestProperty("Cookie", cookies.substring(0,43));//设置获取的cookie
				session1.removeAttribute("Cookie");
			}

			// 建立实际的连接
			httpConn.connect();
			// 响应头部获取
			Map<String, List<String>> headers = httpConn.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : headers.keySet()) {
				System.out.println(key + "\t：\t" + headers.get(key));
				if("Set-Cookie".equals(key)){
					HttpSession session = request.getSession();
					List<String> cookie = headers.get(key);
					session.setAttribute("Cookie",cookie.get(0).substring(0,43));
				}
			}
			// 定义BufferedReader输入流来读取URL的响应,并设置编码方式
			in = new BufferedReader(new InputStreamReader(httpConn
					.getInputStream(), "utf-8"));
			String line;
			// 读取返回的内容
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
}